############################################
# Author: xiongjunfeng
# For: Auto install zabbix-agent
# Version: 2.0
# PowerShell: 4.0
# System: Windows 2012 R2
##############################################

$ZabbixServer="192.168.30.75"

# SSL 证书问题
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

# 下载安装文件
wget -OutFile C:\zabbix_agent.zip https://www.zabbix.com/downloads/3.4.6/zabbix_agents_3.4.6.win.zip

# 解压函数传入 压缩文件路径,解压路径
Function Unzip-File()
{
    param([string]$ZipFile,[string]$TargetFolder)
    # 如果文件夹不存在则创建
    if(!(Test-Path $TargetFolder))
    {
        mkdir $TargetFolder
    }
    $shellApp = New-Object -ComObject Shell.Application
    $files = $shellApp.NameSpace($ZipFile).Items()
    $shellApp.NameSpace($TargetFolder).CopyHere($files)
}
# 将安装文件解压
Unzip-File -ZipFile C:\zabbix_agent.zip -TargetFolder C:\zabbix_agent

# 删除默认配置文件
rm C:\zabbix_agent\conf\zabbix_agentd.win.conf

# 创建配置文件
$hostname=hostname
Add-Content -value "LogFile=C:\zabbix_agent\zabbix.log" C:\zabbix_agent\conf\zabbix_agentd.win.conf
Add-Content -value "Server=$ZabbixServer" C:\zabbix_agent\conf\zabbix_agentd.win.conf
Add-Content -value "Hostname=$hostname" C:\zabbix_agent\conf\zabbix_agentd.win.conf
Add-Content -value "ServerActive=$ZabbixServer" C:\zabbix_agent\conf\zabbix_agentd.win.conf 

# 判断系统类型
$sysinfo=(systeminfo.exe)[14]
$sysinfonew=$sysinfo.Replace("系统类型:         ","")

# 注册服务
if ($sysinfonew -like "x64-based PC" ){
    C:\zabbix_agent\bin\win64\zabbix_agentd.exe --config C:\zabbix_agent\conf\zabbix_agentd.win.conf --install
}else {
    C:\zabbix_agent\bin\win32\zabbix_agentd.exe --config C:\zabbix_agent\conf\zabbix_agentd.win.conf --install
}

# 防火墙
netsh advfirewall firewall add rule name="Zabbix-Agent" dir=in localport=10050 protocol=TCP action=allow

# 启动服务
Start-Service "Zabbix Agent"

# 删除安装包
rm C:\zabbix_agent.zip
